package de.uni.kassel.campusappver3.crawler;

import java.util.regex.Matcher;

import de.uni.kassel.campusappver3.model.CrawlerReturnValue;

/**
 * crawls the NVV site to get the trainschedule of "Muhardstrasse universität"
 * you have to set the time as a parm.
 * 
 * start crawl:
 *  Crawler asd = new NVVCrawler(this);   
    Object[] parms = {"10:10"}; // <-- time
    asd.fetch(parms);


 * onCrawldone:
 * for (String key : crv.getKeys()) {
			System.out.println("######################################");
			System.out.println("time: " + crv.getValue(key).get(0));
			System.out.println("tram: " + crv.getValue(key).get(1));
			System.out.println("direction: " + crv.getValue(key).get(2));
		}
 * @author ckonze
 *
 */
public class NVVCrawler extends Crawler{
	
	private static final String URL_PRE = "http://auskunft.nvv.de/nvv/bin/jp/stboard.exe/" +
										 "dn?L=vs_rmv.vs_nvv&showStBoard=yes&input=2200057&time=";
	private static final String URL_POST = "&start=yes";
	

	public NVVCrawler(ICrawl listener) {
		super(listener);
	}

	@Override
	protected CrawlerReturnValue backgoundCrawl(Object[] params,CrawlerReturnValue crv){
		try {
			String time = (String) params[0];
			int i = 0;
			
			// get meals
			Matcher mat = getUrlMatcher(URL_PRE + time + URL_POST,
					"<tr class=\"depboard(.*?)</tr");
			while(mat.find()){	
				// get time
				Matcher timeMat = getStringMatcher(mat.group(0), "time\">(.*?)</td>");
				timeMat.find();
				String toa = timeMat.group(0);
				toa = toa.substring(6, toa.length()-5);
				
				// get tram id
				Matcher tramMat = getStringMatcher(mat.group(0), "src=(.*?)>(.*?)</a>");
				tramMat.find();
				String tram = removeTagsEntitys(tramMat.group(0)).replaceAll("s(.*?)>\\s", "");
				
				// get direction
				Matcher directionMat = getStringMatcher(mat.group(0), "<strong>(.*?)>(.*?)</a>");
				directionMat.find();
				String direction = removeTagsEntitys(directionMat.group(0));				
				
				//fill returnvalue
				crv.appendValue(Integer.toString(i), toa);
				crv.appendValue(Integer.toString(i), tram);
				crv.appendValue(Integer.toString(i), direction);
				
				i++;				
			}
			return crv;
			
		} catch (Exception e) {
			System.out.println("Error in AsyncTask:" + e.getStackTrace());
			e.printStackTrace();
		}
		return null;
	}

}
